//
//  NDIDAuthenticationView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/17.
//

import SwiftUI
import AVFoundation

struct NDIDAuthenticationView: View, TitledView {
    var navigationTitle: String {
        return title ?? "Identity information"
    }
    
    let title: String?
    let orderNum: String
    let productId: Int
    let stepType: IDCardStepType
    
    @StateObject private var viewModel: NDIDCardViewModel
    
    init(title: String?, orderNum: String, productId: Int, stepType: IDCardStepType = .upload) {
        self.title = title
        self.orderNum = orderNum
        self.productId = productId
        self.stepType = stepType
        self._viewModel = StateObject(wrappedValue: NDIDCardViewModel(orderNum: orderNum,
                                                                      productId: productId,
                                                                      stepType: stepType))

    }
    
    @State private var contentHeight: CGFloat = 0
    
    @Environment(\.navigationManager) var navManager
    @State private var showImagePicker = false
    @State private var selectedImage: UIImage?
    @State private var showPermissAlert = false
    
    var body: some View {
        
        let permissButtons: [NDPopupButton] = [
            NDPopupButton.init(localizedString("Open setting")) {
                showPermissAlert = false
                UIApplication.shared.openAppSettings()
            },
            NDPopupButton.init(localizedString("Cancel"), style: .underline) {
                showPermissAlert = false
            }
        ]
        
        let navigationConfig = NavigationConfig(
            title: navigationTitle,
            showSystemBackButton: false
        )
        NDAuthenBaseView(navigationConfig: navigationConfig) {
            VStack {
                Spacer()
                    .frame(height: 20)
                HStack {
                    ForEach(IDCardStepType.allCases, id: \.self) { type in
                        Button(action: {
                        }) {
                            NDIDCardStepTopView(stepType: type,
                                                isSelected: viewModel.stepType == type)
                        }
                    }
                }
                
                speechBubbleShape
                
                Spacer()
                
                nextStepButton
            }
            .padding(.horizontal, 16)
        }
        .onAppear(perform: {
            viewModel.requestCustomerDetailInfo()
        })
        .onChange(of: viewModel.isLoading) { isLoading in
            DispatchQueue.main.async {
                if isLoading {
                    NDProgressHUD.show()
                } else {
                    if viewModel.errorMessage == nil {
                        NDProgressHUD.dismiss()
                    }
                }
            }
        }
        .onChange(of: viewModel.errorMessage) { msg in
            NDProgressHUD.showInfo(msg)
        }
        .onChange(of: viewModel.saveCardInfoSucces) { success in
            if success {
                viewModel.stepType = .faceReco
                viewModel.showCardInfoAlert = false
            }
        }
        .onChange(of: viewModel.uploadFaceSuccess) { success in
            NotificationCenter.default.post(name: .followUpCurrentProductNotification,
                                            object: nil,
                                            userInfo: nil)
        }
        .fullScreenCover(isPresented: $showImagePicker) {
            NDImagePicker(selectedImage: $selectedImage,
                          sourceType: .camera,
                          isFront: viewModel.stepType == .faceReco,
                          onImageSelected: { image in
                viewModel.uploadImage(image: image)
            })
            .ignoresSafeArea()
        }
        .overlay(
             Group {
                 // 确认信息弹窗
                 if viewModel.showCardInfoAlert {
                     Color.black.opacity(0.3)
                         .edgesIgnoringSafeArea(.all)
                         .onTapGesture {
                             viewModel.showCardInfoAlert = false
                         }
                     
                     confirmInfoAlertView
                         .transition(.scale.combined(with: .opacity))
                 }
             }
         )
        .ndCustomPopupOnWindow(isPresented: $viewModel.showDatePickerAlert,
                               style: .actionSheet,
                               onDismissCompleted: {
            viewModel.showCardInfoAlert = true
        }) {
            let selectedDate = DateFormatterUtility.shared.date(from: viewModel.birthday) ?? (DateFormatterUtility.shared.date(from: "01-01-1990") ?? Date())
            NDCalendarPicker(selectedDate: selectedDate,
                             onDateSelected: { date in
                viewModel.selectedDate = date
                viewModel.showDatePickerAlert = false
            })
            .background(Color(hex: "#FFFFFF"))
        }
        .ndAlertOnWindow(isPresented: $showPermissAlert,
                         title: "",
                         tips: nil,
                         message: localizedString("NSCameraUsageDescription"),
                         backgroundImage: "common_alert_bg",
                         buttons: permissButtons)
    }
    
    var speechBubbleShape: some View {
        Group {
            if viewModel.stepType == .upload || viewModel.stepType == .faceReco  {
                ZStack {
                    NDSpeechBubbleShape(
                        cornerRadius: 16,
                        arrowHeight: 16,
                        arrowWidth: 60,
                        arrowPosition: viewModel.arrowPosition
                    )
                    .fill(Color(hex: "#FFFFFF"))
                    .overlay(
                        NDSpeechBubbleShape(
                            cornerRadius: 16,
                            arrowHeight: 16,
                            arrowWidth: 60,
                            arrowPosition: viewModel.arrowPosition
                        )
                        .stroke(Color(hex: "#271F24"), lineWidth: 1)
                    )
                    .frame(height: contentHeight)

                    currentContentView
                }
            } else {
                currentContentView
            }
        }
    }
    
    // 定义高度偏好键
    struct HeightPreferenceKey: PreferenceKey {
        static var defaultValue: CGFloat = 0
        static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
            value = nextValue()
        }
    }
    
    var currentContentView: some View {
        Group {
            if viewModel.stepType == .upload {
                idCardContentView
                    .onTapGesture {
                        requestCameraPermission()
                    }
            } else if viewModel.stepType == .faceReco {
                faceContentView
                    .onTapGesture {
                        requestCameraPermission()
                    }
            } else {
                completedInfoView
                    .offset(y: -60)
            }
        }
    }

    var idCardContentView: some View {
        VStack(spacing: 24) {
            VStack {
                Image(systemName: "plus")
                    .frame(width: 20, height: 20)
                    .foregroundColor(Color(hex: "#271F24"))
                    .padding(.top, 25)
                Text(localizedString("Upload your ID card"))
                    .frame(maxWidth: .infinity)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color(hex: "#271F24"))
                    .padding(.bottom, 25)
            }
            .background(Color(hex: "#FFF4F0"))
            .cornerRadius(12)
            .padding(.top, 40)
            
            Image(viewModel.stepType.tipsImgName)
                .resizable()
                .scaledToFit()
                .padding(.bottom, 24)
        }
        .overlay(
            GeometryReader { geometry in
                Color.clear
                    .preference(key: HeightPreferenceKey.self,
                                value: geometry.size.height)
            }
        )
        .padding(.horizontal, 24)
        .onPreferenceChange(HeightPreferenceKey.self) { height in
            contentHeight = height
        }
    }
    
    var completedInfoView: some View {
        VStack {
            Image(viewModel.stepType.iconImgName)
                .resizable()
                .scaledToFit()
                .padding(.bottom, 24)
                .zIndex(999)
            
            VStack(spacing: 16) {
                Text(localizedString("Complete Certification"))
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundColor(Color(hex: "#666666"))
                    .padding(.top, 60)
               
                completedTextView
                    .padding(.bottom, 16)
            }
            .frame(maxWidth: .infinity)
            .background(Color(hex: "#FFFFFF"))
            .cornerRadius(30)
            .padding(.top, -90)
            .zIndex(1)

            Spacer()
        }
        .frame(maxWidth: .infinity)
    }
    
    var alertDateButton: some View {
        Group {
            HStack {
                PlaceholderText(text: viewModel.birthday,
                                placeholder: localizedString("Birthday"))
                Spacer()
                Image(systemName: "arrow.right")
                    .foregroundColor(Color(hex: "#271F24"))
            }
            .padding(8)
            .frame(height: 48)
            .frame(maxWidth: .infinity)
            .font(.system(size: 14, weight: .medium))
            .foregroundColor(Color(hex: "#271F24"))
            .background(Color(hex: "#F7F8F9"))
            .cornerRadius(8)
            .keyboardType(.default)
            .onTapGesture {
                if viewModel.showCardInfoAlert == true {
                    viewModel.showCardInfoAlert = false
                    viewModel.showDatePickerAlert = true
                }
            }
        }
    }
    
    var confirmInfoAlertView: some View  {
        VStack(spacing: 0) {
            Spacer()
            
            VStack(spacing: 0) {
                Spacer(minLength: 20)
                Text(localizedString("Confirm again"))
                    .font(.system(size: 20, weight: .bold))
                    .foregroundColor(Color(hex: "#FFFFFF"))
                    .multilineTextAlignment(.leading)
                    .padding(.top, 30)
                    .padding(.horizontal, 30)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .shadow(color: .black, radius: 1, x: 0, y: 0)
                    .shadow(color: .black, radius: 1, x: 0, y: 0)
                    .shadow(color: .black, radius: 1, x: 0, y: 0)
                
                VStack(spacing: 24) {
                    confirmInfoTextFieldView
                        .padding(.horizontal, 16)
                    Spacer()
                    confirmAlertButton
                        .padding(.bottom, 20)
                }
                .background(Color(hex: "#FFFFFF"))
                .cornerRadius(20)
                .padding(.horizontal, 18)
                .padding(.top, 30)
                .padding(.bottom, 16)
            }
            .background(
                Image("id_card_bg_alert")
                    .resizable()
                    .scaledToFit() // 保持图片比例自适应
            )
            .cornerRadius(20)
            .padding(.horizontal, 16) // 左右距离屏幕16
            .fixedSize(horizontal: false, vertical: true) // 高度自适应
            
            Spacer()
        }
    }
    
    var confirmInfoTextFieldView: some View {
        Group {
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("Real name"))
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                TextField(localizedString("Real name"), text: $viewModel.realName)
                    .padding(8)
                    .frame(height: 48)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color(hex: "#271F24"))
                    .background(Color(hex: "#F7F8F9"))
                    .cornerRadius(8)
                    .keyboardType(.default)
            }
            .padding(.top, 15)
            
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("Id number"))
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                TextField(localizedString("Id number"), text: $viewModel.idNumber)
                    .padding(8)
                    .frame(height: 48)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color(hex: "#271F24"))
                    .background(Color(hex: "#F7F8F9"))
                    .cornerRadius(8)
                    .keyboardType(.default)
            }
            
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("Birthday"))
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                alertDateButton
            }
            .padding(.bottom, 24)
        }
    }
    
    var completedTextView: some View {
        VStack(spacing: 24) {
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("Real name"))
                    .padding(.horizontal, 8)
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                    .frame(maxWidth: .infinity, alignment: .leading) // 左侧对齐
                Text(viewModel.realName)
                    .padding(.horizontal, 8)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color(hex: "#271F24"))
                    .frame(maxWidth: .infinity, alignment: .leading) // 左侧对齐
            }
            .padding(.top, 15)
            
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("Id number"))
                    .padding(.horizontal, 8)
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                    .frame(maxWidth: .infinity, alignment: .leading) // 左侧对齐
                Text(viewModel.idNumber)
                    .padding(.horizontal, 8)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color(hex: "#271F24"))
                    .frame(maxWidth: .infinity, alignment: .leading) // 左侧对齐
            }
            
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("Birthday"))
                    .padding(.horizontal, 8)
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                    .frame(maxWidth: .infinity, alignment: .leading) // 左侧对齐
                Text(viewModel.birthday)
                    .padding(.horizontal, 8)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color(hex: "#271F24"))
                    .frame(maxWidth: .infinity, alignment: .leading) // 左侧对齐
            }
            .padding(.bottom, 16)
        }
        .frame(maxWidth: .infinity)
        .background(Color(hex: "#FFF4F0"))
        .cornerRadius(12)
        .padding(.horizontal, 16)
    }
    
    var confirmAlertButton: some View {
        Group {
            Button(action: confirmAction) {
                Text(localizedString("Confirmed to be correct"))
                    .font(.system(size: 18, weight: .bold))
                    .foregroundColor(Color(hex: "#FFFFFF"))
                    .padding(.horizontal, 15)
                    .padding(.vertical, 10)
                    .frame(height: 41)
                    .background(Color(hex: "#271F24"))
                    .clipShape(Capsule())
                    .contentShape(Rectangle())
                    .padding(.bottom, 10)
            }
            .padding(.horizontal, 16)
        }
    }

    var faceContentView: some View {
        VStack(spacing: 24) {
            VStack(spacing: 16)  {
                Image("people")
                    .resizable()
                    .frame(width: 100, height: 100)
                    .scaledToFit()

                Text(localizedString("Start the authentication"))
                    .font(.system(size: 14, weight: .medium))
                .foregroundColor(Color(hex: "#FFFFFF"))
                .padding(.horizontal, 16)
                .padding(.vertical, 5)
                .background(Color(hex: "#271F24"))
                .clipShape(Capsule())
                .contentShape(Rectangle())
                .padding(.bottom, 10)
                .frame(height: 33)
            }
            .padding(.top, 40)
            
            Image(viewModel.stepType.tipsImgName)
                .resizable()
                .scaledToFit()
                .padding(.bottom, 24)
        }
        .overlay(
            GeometryReader { geometry in
                Color.clear
                    .preference(key: HeightPreferenceKey.self,
                                value: geometry.size.height)
            }
        )
        .padding(.horizontal, 24)
        .onPreferenceChange(HeightPreferenceKey.self) { height in
            contentHeight = height
        }
    }
    
    var nextStepButton: some View {
        Button(action: nextStepAction) {
            Text(localizedString("Next step"))
                .frame(maxWidth: .infinity)
                .font(.system(size: 18, weight: .bold))
                .foregroundColor(Color(hex: "#FFFFFF"))
                .padding(.horizontal, 15)
                .padding(.vertical, 10)
                .frame(height: 48)
                .background(Color(hex: "#271F24"))
                .clipShape(Capsule())
                .contentShape(Rectangle())
                .padding(.bottom, 10)
        }
        .padding(.horizontal, 16)
    }
    
    func confirmAction() {
        viewModel.saveCardInfo()
    }
    
    func nextStepAction() {
        switch viewModel.stepType {
        case .upload, .faceReco:
            requestCameraPermission()
        case .completed:
            NotificationCenter.default.post(name: .followUpCurrentProductNotification,
                                            object: nil,
                                            userInfo: nil)
        }
    }
    
    func requestCameraPermission() {
        self.showPermissAlert = false
        // 记录开始时间
        if viewModel.stepType == .faceReco {
            viewModel.faceStartTime = Int(Date().timeIntervalSince1970)
        } else {
            viewModel.idStartTime = Int(Date().timeIntervalSince1970)
        }
        
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        print("相机权限状态: \(status.rawValue)")
        
        switch status {
        case .authorized:
            // 已有权限，直接打开相机
            DispatchQueue.main.async {
                showImagePicker = true
            }
            
        case .notDetermined:
            // 请求权限
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        showImagePicker = true
                    } else {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                            self.showPermissAlert = true
                        }
                    }
                }
            }
            
        case .denied, .restricted:
            DispatchQueue.main.async {
                self.showPermissAlert = true
            }
            
        @unknown default:
            DispatchQueue.main.async {
                self.showPermissAlert = true
            }
        }
    }
}
